<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">      
      <el-form-item label="字典类型" prop="dictType">
        <el-input
          v-model="queryParams.dictType"
          size="small"
          :disabled="true"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="字典名称" prop="dictName">
        <el-input
          v-model="queryParams.dictName"
          size="small"
          :disabled="true"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>  
      <el-form-item label="数据名称" prop="dictLabel">
        <el-input
          v-model="queryParams.dictLabel"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>  

      <el-form-item>
	    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:treeData:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border stripe
      ref="table"
      v-loading="loading"
      :data="dataList"
      row-key="dataId"
      lazy
      :load="loadChild"
      :default-expand-all="isExpandAll"
      :header-cell-style="getRowClass"
      :cell-style="rowStyle"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="名称" align="left" prop="dictLabel" :show-overflow-tooltip="true"/>
      <el-table-column label="Code" align="left" prop="dictCode" :show-overflow-tooltip="true"/>
      <el-table-column label="排序" align="center" width="60"   prop="dictSort" />
      <el-table-column label="状态" align="center" width="100"  prop="status" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:treeData:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['system:treeData:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:treeData:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改字典数据对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        
        <el-form-item label="上级节点" prop="parentId">
          <treeselect
                  v-model="form.parentId"
                  :options="dataOptions"
                  :load-options="loadOptions"
                  @select="nodeClick"
                  placeholder="选择上级节点"
                />
        </el-form-item>

        <el-form-item label="字典标签" prop="dictLabel">
          <el-input v-model="form.dictLabel" placeholder="请输入字典标签" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
             <el-form-item label="排序" prop="dictSort">
                <el-input-number v-model="form.dictSort" controls-position="right" :min="0" />
              </el-form-item>
          </el-col>
          <el-col :span="12">
              <el-form-item label="状态">
                <el-radio-group v-model="form.status">
                  <el-radio
                    v-for="dict in dict.type.sys_normal_disable"
                    :key="dict.value"
                    :label="dict.value"
                  >{{dict.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
          </el-col>
        </el-row>
       
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTreeData, getTreeData, delTreeData, addTreeData, updateTreeData, listTreeSelect } from "@/api/system/tree/data";
import { getTree } from "@/api/system/tree";

import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "TreeData",
  dicts: ['sys_normal_disable'],
  components: {
    Treeselect
  },
  data() {
    return {
      // 数据标签回显样式
      listClassOptions: [
        {
          value: "default",
          label: "默认"
        },
        {
          value: "primary",
          label: "主要"
        },
        {
          value: "success",
          label: "成功"
        },
        {
          value: "info",
          label: "信息"
        },
        {
          value: "warning",
          label: "警告"
        },
        {
          value: "danger",
          label: "危险"
        }
      ],
      // 遮罩层
      loading: true,
      dictId: null,
      // 显示搜索条件
      showSearch: true,
      // 是否展开，默认全部折叠
      isExpandAll: false,
      // 字典数据表格数据      
      dataList: [],
      // 字典数据树选项
      dataOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        parentId: null,
        dictId: null,
        dictType: null,
        dictName: null,
        dictLabel: null,
        dictCode: null,
        cssClass: null,
        listClass: null,
        isDefault: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        dictId: [
          { required: true, message: "字典主键不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.dictId = this.$route.params && this.$route.params.dictId;
    this.queryParams.dictId = this.dictId ;
    this.form.dictId = this.dictId ;
    this.generalData();
    this.getList();
  },
  methods: {
    generalData() {
      getTree(this.form.dictId).then(response => {
        this.queryParams.dictType = response.data.dictType ;
        this.queryParams.dictName = response.data.dictName ;      
      })
    },
    /** 查询字典数据列表 */
    getList() {
      this.loading = true;
      listTreeData(this.queryParams).then(response => {
        this.dataList = response.data;
        this.loading = false;
      });
    },
    loadChild(row, treeNode, resolve) {
        listTreeData({parentId: row.dataId, dictId: this.dictId}).then(response => {
          resolve(response.data)
        });
     },

	  /** 查询字典数据下拉树结构 */
    getTreeselect() {
      listTreeSelect({dictId: this.dictId}).then(response => {
        var treeList = response.data;
        for (var index in treeList) {
          if (treeList[index].hasChildren == true) {
            treeList[index].children = null;  
          }
        }
        this.dataOptions = treeList;
      });
    },
    /** 级连单位下拉树结构 */
    loadOptions({ action, parentNode, callback }) {
      if (action === "LOAD_CHILDREN_OPTIONS") {
        listTreeSelect({ parentId: parentNode.id, dictId: this.dictId }).then(response => {
          var treeList = response.data;
          for (var index in treeList) {
            if (treeList[index].hasChildren == true) {
              treeList[index].children = null;
            }
          }
          parentNode.children = treeList;
          callback();
        });
      } else {
        callback();
      }
    },
    
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        dataId: null,
        parentId: null,
        dictId: this.dictId,
        dictLabel: null,
        dictCode: null,
        dictSort: null,
        cssClass: null,
        listClass: null,
        isDefault: null,
        status: "0",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.generalData();
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.dataId && row != undefined) {
        this.form.parentId = row.dataId;
      } else {
        this.form.parentId = 0;
      }
      this.open = true;
      this.title = "添加字典数据";

      setTimeout(() => {
        //解决下拉懒加载树无法获取未加载的子节点中文问题
        var objs = document.getElementsByTagName("div");
        for (var i = 0; i < objs.length; i++) {
          if (objs[i].className == "vue-treeselect__single-value") {
            if (row != null && row.dataId && row != undefined) {
              objs[i].innerHTML = row.dictLabel;
            } else {
              objs[i].innerHTML = "";
            }
              
          }
        }
      }, 200);
    },

    nodeClick(node, instanceId) {
      let objs = document.getElementsByTagName("div");
      for (var i = 0; i < objs.length; i++) {
        if (objs[i].className == "vue-treeselect__single-value") {
          objs[i].innerHTML = node.label;
        }
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      if (row != null) {
        this.form.parentId = row.parentId;
      }
      getTreeData(row.dataId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改字典数据";
        getTreeData(this.form.parentId).then( res => {
            var parentNode = res.data ;
            setTimeout(() => {
            //解决下拉懒加载树无法获取未加载的子节点中文问题
              var objs = document.getElementsByTagName("div");
              for (var i = 0; i < objs.length; i++) {
                if (objs[i].className == "vue-treeselect__single-value") {
                  if(parentNode != undefined) {
                    objs[i].innerHTML = parentNode.dictLabel;
                  } else {
                    objs[i].innerHTML = '';
                  }
                }
              }
            }, 200);
          }
        )        
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.dataId != null) {
            updateTreeData(this.form).then(response => {
              this.refresh(this.form.parentId, this.dictId);              
            });
          } else {
            addTreeData(this.form).then(response => {
                this.refresh(this.form.parentId, this.dictId);
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除字典数据编号为"' + row.dataId + '"的数据项？').then(function() {
        return delTreeData(row.dataId);
      }).then(() => {
        this.refresh(row.parentId, this.dictId);        
      }).catch(() => {});
    },

    refresh(parentId, dictId) {
      if(parentId != 0) {
            listTreeData({parentId: parentId, dictId: dictId}).then(response => {
            this.$set(this.$refs.table.store.states.lazyTreeNodeMap, parentId, response.data)
            this.$modal.msgSuccess("操作成功");
            this.open = false;
          });
        } else {
          this.getList();
          this.$modal.msgSuccess("操作成功");
          this.open = false;
        }
    },
    rowStyle({row, column, rowIndex, columnIndex}){
        //设置表格每行间隔颜色
        if (rowIndex%2===0){
            return "background:#2A3056;border:none;color: #FFFFFF;"
        }
        if (rowIndex%2===1){
            return "background:#2E335E;border:none;color: #FFFFFF;"
        }
    },
    //设置表头背景颜色
    getRowClass({ row, column, rowIndex, columnIndex }) {
        return "background:#363C74;border:none;color: #FFFFFF;";
    },
  }
};
</script>